﻿using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.WindowsMobile.PocketOutlook;

namespace PlaxoSyncWM {
    public class MobileContactsFile {
        public ContactCollection mobileContacts;
        public StreamWriter writeMobileContacts;

        public bool mobileContactsFileExists() {
            return File.Exists(Constants.MobileContacts);
        }

        public void create() {
            if (mobileContactsFileExists()) {
                using (FileStream fs = new FileStream(Constants.MobileContacts, FileMode.CreateNew, FileAccess.Write)) {
                    if (fs.CanWrite)
                        writeData(fs);
                }
            }
            else {
                try {
                    using (FileStream fs = new FileStream(Constants.MobileContacts, FileMode.CreateNew, FileAccess.Write)) {
                        writeData(fs);
                    }
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message, ex.StackTrace);
                }
            }
        }

        public void writeData(FileStream fs) {
            writeMobileContacts = new StreamWriter(fs);
            OutlookSession os = new OutlookSession();
            ContactCollection contacts = os.Contacts.Items;
            foreach (Microsoft.WindowsMobile.PocketOutlook.Contact contact in contacts) {
                string line =
                    String.Format("{0}, {1}, {2}, {3} {4}, {5}", contact.ItemId, contact.FirstName, contact.LastName,
                                  contact.MobileTelephoneNumber, contact.Email1Address, contact.HomeTelephoneNumber);
                writeMobileContacts.WriteLine(line);
            }
            writeMobileContacts.Close();
            writeMobileContacts.Dispose();
            os.Dispose();
            fs.Close();
            fs.Dispose();
        }
    }
}